import { ref, reactive, defineComponent, computed, nextTick, onMounted, watch } from 'vue';
import { useDraggable } from './hooks/use-draggable';
import { Form, Select, Color, Button, Switch, Row, Col } from '@jecloud/ui';
import { encode, decode, getDDItemInfo } from '@jecloud/utils';
import { FIELD_COLOR_CONFIG0, FIELD_COLOR_CONFIG1 } from './hooks/constant/index.js';
import { columns as columnOptions } from './hooks/config';
import VueEvent from '@/helper/event';
import elementResizeDetectorMaker from 'element-resize-detector';

export default defineComponent({
  name: 'DargContainerGroup',
  components: { Row, Col, Select },
  inheritAttrs: false,
  props: {
    data: {
      type: Object,
      default() {
        return {};
      },
    },
    columns: { type: String, default: '3' },
  },
  setup(props, { slots }) {
    const { dragEl, dragClass, removeFn } = useDraggable({ owner: 'group', props });

    let colRef = ref('');
    let width = ref('');
    let peiseRef = ref('');

    let config = decode((props.data.RESOURCEFIELD_OTHERCONFIG || undefined) ?? '{}') ?? {};
    let otherCfgs = reactive({
      quickPositioning: config.quickPositioning || '0', //快速定位
      keepUp: config.keepUp || '0', //保持收起
      noStyle: config.noStyle || '0', //无样式
      titleWidth: config.titleWidth || '', //组内标题宽
      bgColor: config.bgColor || '', //分组框背景
      titleColor: config.titleColor || '', //标题色
      titleBgColor: config.titleBgColor || '', //标题背景色
      borderColor: config.borderColor || '', //边框色
    });
    // 监听变化
    watch(
      () => otherCfgs,
      (newVal) => {
        if (newVal) {
          config = decode(newVal ?? '{}') ?? {};
          Object.keys(otherCfgs).forEach((item) => {
            otherCfgs[item] = config[item];
          });
          // eslint-disable-next-line vue/no-mutating-props
          props.data.RESOURCEFIELD_OTHERCONFIG = encode(otherCfgs);
        }
      },
      { deep: true },
    );

    watch(
      () => props.data.flag,
      (newVal) => {
        const fieldBodyEle = colRef.value.querySelector('.group-body') || '';
        if (newVal) {
          fieldBodyEle && (fieldBodyEle.style.display = 'none');
        } else {
          fieldBodyEle && (fieldBodyEle.style.display = '');
        }
      },
      { deep: true },
    );

    let spanNumber = computed(() => {
      if (props.data.RESOURCEFIELD_COLSPAN >= props.columns) {
        // eslint-disable-next-line vue/no-mutating-props
        props.data.RESOURCEFIELD_COLSPAN = props.columns;
      }
      return Math.ceil((props.data.RESOURCEFIELD_COLSPAN / props.columns) * 24);
    });

    const erd = elementResizeDetectorMaker();
    onMounted(() => {
      const fieldBodyEle = colRef.value.querySelector('.group-body') || '';
      if (props.data.flag) {
        fieldBodyEle && (fieldBodyEle.style.display = 'none');
      } else {
        fieldBodyEle && (fieldBodyEle.style.display = '');
      }
      erd.listenTo(colRef.value, (element) => {
        nextTick(() => {
          // 实时获取宽度，以此显示决定是否显示某些元素
          width.value = element.offsetWidth;
        });
      });
    });

    let style = ref({});
    let isShowColorScheme = ref(false);
    //点击颜色
    const selectFieldColor = (item) => {
      const { bgColor, titleColor, titleBgColor, borderColor } = item;
      Object.assign(otherCfgs, { bgColor, titleColor, titleBgColor, borderColor });
    };

    const showColorScheme = () => {
      let obj = peiseRef.value.getBoundingClientRect();
      if (window.innerHeight - obj.top < 420) {
        style.value.top = obj.top - 420 + 'px';
      } else {
        style.value.top = obj.top + 30 + 'px';
      }

      style.value.left = `${obj.left - 230 > 0 ? obj.left : 230}px`;

      isShowColorScheme.value = !isShowColorScheme.value;
    };

    // 点击分组框是否收起还是展开默认值展开的
    const handleClickField = (e) => {
      // eslint-disable-next-line vue/no-mutating-props
      props.data.flag = !props.data.flag;
    };
    const hideColorScheme = (e) => {
      isShowColorScheme.value = false;
      e.stopPropagation();
    };
    const getPopupContainer = () => {
      return document.body;
    };
    const clickReset = () => {
      // 框内背景颜色: #FFFFFF 标题色：#3F3F3F 标题背景色：#F5F5F5 边框色：#D9D9D9
      otherCfgs.bgColor = '';
      otherCfgs.titleColor = '';
      otherCfgs.titleBgColor = '';
      otherCfgs.borderColor = '';
      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_OTHERCONFIG = encode(otherCfgs);
    };

    const colorSchemeStopPropagation = (e) => {
      e.stopPropagation();
    };

    const handleChangeAttrValue = (key, value) => {
      otherCfgs[key] = value;

      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_OTHERCONFIG = encode(otherCfgs);
    };

    const handleChangeAttrValue2 = (key, value) => {
      // eslint-disable-next-line vue/no-mutating-props
      props.data[key] = value;
    };

    const handleChangeAttrValue3 = (key, value) => {
      if (value >= props.columns) {
        // eslint-disable-next-line vue/no-mutating-props
        props.data[key] = props.columns;
      } else {
        // eslint-disable-next-line vue/no-mutating-props
        props.data[key] = value;
      }
    };

    const handleClick = () => {
      VueEvent.emit('showEditFormFieldConfig', props.data);
    };

    const textareaKeydown = (event) => {
      if (event.ctrlKey && event.keyCode === 13) {
        //ctrl+enter
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      } else if (event.keyCode === 13) {
        //enter
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    };
    const handleBlurTxt = (e) => {
      // eslint-disable-next-line vue/no-mutating-props
      props.data.RESOURCEFIELD_NAME = e.target.innerHTML;
    };

    return () => {
      const { id, RESOURCEFIELD_NAME } = props.data;
      return (
        <Col span={spanNumber.value} key={id} data-id={id} data-type="group">
          <div
            ref={colRef}
            class={['container-group']}
            style={{
              backgroundColor: otherCfgs.bgColor,
              borderColor: otherCfgs.borderColor,
              'margin-bottom': '5px',
            }}
          >
            {/* 别删，解决单击元素周围的任意位置，contenteditable 也会生效的问题*/}
            <div style={{ height: '0.1px', overflow: 'hidden' }}>1111</div>

            <div
              class={['group-header', dragClass, isShowColorScheme.value ? 'filter' : '']}
              style={{ backgroundColor: otherCfgs.titleBgColor }}
            >
              {width.value > 150 ? (
                <span style={{ display: 'flex', flex: '1', width: 0 }}>
                  <i
                    onClick={handleClick}
                    class={[
                      'icon',
                      getDDItemInfo('JE_FUNC_FIELD_XTYPE', props.data.RESOURCEFIELD_XTYPE)?.icon ||
                        'fal fa-inbox',
                    ]}
                  ></i>
                  <span
                    class={{ text: true }}
                    title={RESOURCEFIELD_NAME}
                    style={{ color: otherCfgs.titleColor }}
                    contenteditable
                    onBlur={handleBlurTxt}
                    onKeydown={textareaKeydown}
                  >
                    {RESOURCEFIELD_NAME}
                  </span>
                  <i
                    style="margin-left: 5px"
                    onClick={handleClickField}
                    class={[props.data.flag ? 'icon fal fa-angle-down' : 'icon fal fa-angle-up']}
                  ></i>
                </span>
              ) : null}

              <div class="actions">
                {width.value > 340 ? (
                  <span class="peise" ref={peiseRef} onClick={showColorScheme}>
                    配色 <i class="fal fa-angle-down "></i> &nbsp;&nbsp;
                    {isShowColorScheme.value ? (
                      <div class="dropmenuWrap" onClick={hideColorScheme}></div>
                    ) : null}
                    {isShowColorScheme.value ? (
                      <div
                        onClick={colorSchemeStopPropagation}
                        class="dropmenu"
                        style={{ top: style.value.top, left: style.value.left }}
                      >
                        <div style="padding: 0px 20px">
                          <Form.Item label="框内背景颜色">
                            <Color
                              onChange={(e) => handleChangeAttrValue('bgColor', e.target.value)}
                              onSelect={(e) => handleChangeAttrValue('bgColor', e.value)}
                              v-model:value={otherCfgs.bgColor}
                              style={{ width: '150px' }}
                            />
                          </Form.Item>
                          <Form.Item label="边框颜色">
                            <Color
                              onChange={(e) => handleChangeAttrValue('borderColor', e.target.value)}
                              onSelect={(e) => handleChangeAttrValue('borderColor', e.value)}
                              v-model:value={otherCfgs.borderColor}
                              style={{ width: '150px' }}
                            />
                          </Form.Item>
                          <Form.Item label="标题颜色">
                            <Color
                              onChange={(e) => handleChangeAttrValue('titleColor', e.target.value)}
                              onSelect={(e) => handleChangeAttrValue('titleColor', e.value)}
                              v-model:value={otherCfgs.titleColor}
                              style={{ width: '150px' }}
                            />
                          </Form.Item>
                          <Form.Item label="标题背景颜色">
                            <Color
                              onChange={(e) =>
                                handleChangeAttrValue('titleBgColor', e.target.value)
                              }
                              onSelect={(e) => handleChangeAttrValue('titleBgColor', e.value)}
                              v-model:value={otherCfgs.titleBgColor}
                              style={{ width: '150px' }}
                            />
                          </Form.Item>
                        </div>

                        <div class="change-field-color">
                          <div class="color-container">
                            {FIELD_COLOR_CONFIG0.map((colorItem) => {
                              return (
                                <span
                                  style={{
                                    background: colorItem.titleBgColor,
                                  }}
                                  onClick={() => selectFieldColor(colorItem)}
                                ></span>
                              );
                            })}
                          </div>
                          <div style="margin: 20px 0" class="color-container">
                            {FIELD_COLOR_CONFIG1.map((colorItem) => {
                              return (
                                <span
                                  style={{
                                    background: colorItem.titleBgColor,
                                  }}
                                  onClick={() => selectFieldColor(colorItem)}
                                ></span>
                              );
                            })}
                          </div>

                          <Button type="text" style="text-align: center" onClick={clickReset}>
                            一键清空
                          </Button>
                        </div>
                      </div>
                    ) : null}
                    {isShowColorScheme.value ? (
                      <div class="dropmenuWrap" onClick={hideColorScheme}></div>
                    ) : null}
                  </span>
                ) : null}
                {width.value > 300 ? (
                  <Switch
                    mode="checkbox"
                    defaultChecked={otherCfgs.keepUp}
                    v-model:value={otherCfgs.keepUp}
                    label={width.value > 550 ? '默认收起' : null}
                  ></Switch>
                ) : null}
                {width.value > 350 ? (
                  <Switch
                    mode="checkbox"
                    defaultChecked={otherCfgs.noStyle}
                    v-model:value={otherCfgs.noStyle}
                    label={width.value > 550 ? '无样式' : null}
                  ></Switch>
                ) : null}
                {width.value > 400 ? (
                  <Switch
                    mode="checkbox"
                    defaultChecked={otherCfgs.quickPositioning}
                    v-model:value={otherCfgs.quickPositioning}
                    label={width.value > 550 ? '快速定位' : null}
                  ></Switch>
                ) : null}
                &nbsp;&nbsp;
                <Select
                  allowClear={false}
                  v-model:value={props.data.RESOURCEFIELD_COLS}
                  size="small"
                  get-popup-container={getPopupContainer}
                  options={columnOptions}
                  onChange={(val) => handleChangeAttrValue2('RESOURCEFIELD_COLS', val)}
                  style="margin-right:10px"
                />
                <Select
                  allowClear={false}
                  get-popup-container={getPopupContainer}
                  v-model:value={props.data.RESOURCEFIELD_COLSPAN}
                  size="small"
                  options={columnOptions}
                  onChange={(val) => handleChangeAttrValue3('RESOURCEFIELD_COLSPAN', val)}
                />
                <i class="fal fa-times remove-icon" onClick={removeFn}></i>
              </div>
            </div>
            <Row class="group-body" gutter={[4, 4]} ref={dragEl} data-id={id}>
              {slots.default?.({ columns: props.data.RESOURCEFIELD_COLS })}
            </Row>
          </div>
        </Col>
      );
    };
  },
});
